<template>
  <view class="page-container">
    <!-- 扫码区域 -->
    <view class="scan-container">
      <view class="scan-frame">
        <view class="scan-area">
          <view class="scan-line" :class="{ scanning: isScanning }"></view>
          <view class="corner top-left"></view>
          <view class="corner top-right"></view>
          <view class="corner bottom-left"></view>
          <view class="corner bottom-right"></view>
        </view>
      </view>
      
      <view class="scan-tips">
        <text class="tips-text">将优惠券二维码放入框内，即可自动扫描</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn primary-btn" @click="startScan" :disabled="isScanning">
        {{ isScanning ? '扫描中...' : '开始扫描' }}
      </button>
      <button class="action-btn secondary-btn" @click="toggleFlash">
        {{ flashOn ? '关闭闪光灯' : '打开闪光灯' }}
      </button>
      <button class="action-btn secondary-btn" @click="showManualInput">
        手动输入
      </button>
    </view>

    <!-- 最近核销记录 -->
    <view class="recent-records" v-if="recentRecords.length > 0">
      <view class="section-title">
        <uni-icons type="clock" size="16" color="#666"></uni-icons>
        <text>最近核销</text>
      </view>
      <view class="record-list">
        <view 
          v-for="record in recentRecords" 
          :key="record.id" 
          class="record-item"
          @click="goToDetail(record.id)"
        >
          <view class="record-info">
            <text class="coupon-name">{{ record.coupon_name }}</text>
            <text class="verify-time">{{ formatTime(record.created_at) }}</text>
          </view>
          <uni-tag 
            :text="getVerifyStatusText(record.status)" 
            :type="getVerifyStatusType(record.status)" 
            size="small"
          ></uni-tag>
        </view>
      </view>
    </view>

    <!-- 手动输入弹窗 -->
    <uni-popup ref="manualInputPopup" type="center">
      <view class="manual-input-modal">
        <view class="modal-header">
          <text class="modal-title">手动输入优惠券码</text>
        </view>
        <view class="modal-body">
          <uni-easyinput 
            v-model="manualCode" 
            placeholder="请输入优惠券码"
            :inputBorder="false"
            class="code-input"
          ></uni-easyinput>
        </view>
        <view class="modal-footer">
          <button class="modal-btn cancel-btn" @click="closeManualInput">取消</button>
          <button class="modal-btn confirm-btn" @click="handleManualVerify" :loading="verifying">确认</button>
        </view>
      </view>
    </uni-popup>

    <!-- 核销结果弹窗 -->
    <uni-popup ref="resultPopup" type="center">
      <view class="result-modal">
        <view class="result-icon" :class="verifyResult.success ? 'success' : 'error'">
          <uni-icons 
            :type="verifyResult.success ? 'checkmarkempty' : 'closeempty'" 
            size="48" 
            color="#fff"
          ></uni-icons>
        </view>
        <view class="result-title">
          {{ verifyResult.success ? '核销成功' : '核销失败' }}
        </view>
        <view class="result-content" v-if="verifyResult.data">
          <view class="result-item">
            <text class="label">优惠券名称:</text>
            <text class="value">{{ verifyResult.data.coupon_name }}</text>
          </view>
          <view class="result-item">
            <text class="label">优惠金额:</text>
            <text class="value">¥{{ (verifyResult.data.discount_amount || 0) / 100 }}</text>
          </view>
          <view class="result-item" v-if="verifyResult.data.order_no">
            <text class="label">订单号:</text>
            <text class="value">{{ verifyResult.data.order_no }}</text>
          </view>
        </view>
        <view class="result-message" v-if="verifyResult.message">
          {{ verifyResult.message }}
        </view>
        <button class="result-btn" @click="closeResultModal">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { verifyCouponByCode, fetchVerifyRecords } from '@/api/coupon';

interface VerifyRecord {
  id: number;
  coupon_name: string;
  status: number;
  created_at: number;
}

interface VerifyResult {
  success: boolean;
  message?: string;
  data?: any;
}

const isScanning = ref(false);
const flashOn = ref(false);
const manualCode = ref('');
const verifying = ref(false);
const recentRecords = ref<VerifyRecord[]>([]);

const manualInputPopup = ref();
const resultPopup = ref();

const verifyResult = reactive<VerifyResult>({
  success: false,
  message: '',
  data: null
});

// 开始扫描
const startScan = () => {
  // #ifdef APP-PLUS
  isScanning.value = true;
  
  // 调用原生扫码功能
  uni.scanCode({
    success: (res) => {
      handleScanResult(res.result);
    },
    fail: (err) => {
      console.error('扫码失败:', err);
      uni.showToast({
        title: '扫码失败',
        icon: 'none'
      });
    },
    complete: () => {
      isScanning.value = false;
    }
  });
  // #endif
  
  // #ifdef H5
  // H5环境下的模拟扫码
  uni.showModal({
    title: '模拟扫码',
    editable: true,
    placeholderText: '请输入优惠券码',
    success: (res) => {
      if (res.confirm && res.content) {
        handleScanResult(res.content);
      }
    }
  });
  // #endif
};

// 处理扫码结果
const handleScanResult = async (code: string) => {
  if (!code) return;
  
  try {
    uni.showLoading({ title: '核销中...' });
    const result = await verifyCouponByCode(code);
    
    verifyResult.success = true;
    verifyResult.data = result;
    verifyResult.message = '核销成功';
    
    // 刷新最近记录
    getRecentRecords();
    
  } catch (error: any) {
    verifyResult.success = false;
    verifyResult.message = error.message || '核销失败';
    verifyResult.data = null;
  } finally {
    uni.hideLoading();
    resultPopup.value.open();
  }
};

// 切换闪光灯
const toggleFlash = () => {
  flashOn.value = !flashOn.value;
  // 这里应该调用原生API控制闪光灯
  uni.showToast({
    title: flashOn.value ? '闪光灯已打开' : '闪光灯已关闭',
    icon: 'none'
  });
};

// 显示手动输入弹窗
const showManualInput = () => {
  manualCode.value = '';
  manualInputPopup.value.open();
};

// 关闭手动输入弹窗
const closeManualInput = () => {
  manualInputPopup.value.close();
};

// 手动核销
const handleManualVerify = async () => {
  if (!manualCode.value.trim()) {
    uni.showToast({
      title: '请输入优惠券码',
      icon: 'none'
    });
    return;
  }
  
  verifying.value = true;
  try {
    const result = await verifyCouponByCode(manualCode.value.trim());
    
    verifyResult.success = true;
    verifyResult.data = result;
    verifyResult.message = '核销成功';
    
    // 关闭输入弹窗，显示结果弹窗
    manualInputPopup.value.close();
    resultPopup.value.open();
    
    // 刷新最近记录
    getRecentRecords();
    
  } catch (error: any) {
    verifyResult.success = false;
    verifyResult.message = error.message || '核销失败';
    verifyResult.data = null;
    
    manualInputPopup.value.close();
    resultPopup.value.open();
  } finally {
    verifying.value = false;
  }
};

// 关闭结果弹窗
const closeResultModal = () => {
  resultPopup.value.close();
};

// 获取最近核销记录
const getRecentRecords = async () => {
  try {
    const res = await fetchVerifyRecords({
      page: 1,
      pageSize: 5
    });
    recentRecords.value = res.list || [];
  } catch (error) {
    console.error('获取最近记录失败:', error);
  }
};

// 跳转到详情页
const goToDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/coupons/verify/detail?id=${id}`
  });
};

const getVerifyStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '成功',
    0: '失败',
    2: '待处理'
  };
  return statusMap[status] || '未知';
};

const getVerifyStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    1: 'success',
    0: 'error',
    2: 'warning'
  };
  return typeMap[status] || 'default';
};

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  if (diff < 60000) { // 1分钟内
    return '刚刚';
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`;
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`;
  } else {
    return date.toLocaleDateString();
  }
};

onLoad(() => {
  getRecentRecords();
});

onUnload(() => {
  // 清理资源
  isScanning.value = false;
  flashOn.value = false;
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #000;
}

.scan-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.scan-frame {
  width: 250px;
  height: 250px;
  position: relative;
}

.scan-area {
  width: 100%;
  height: 100%;
  position: relative;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  
  .scan-line {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, #00ff00, transparent);
    
    &.scanning {
      animation: scanning 2s linear infinite;
    }
  }
  
  .corner {
    position: absolute;
    width: 20px;
    height: 20px;
    border: 3px solid #00ff00;
    
    &.top-left {
      top: -3px;
      left: -3px;
      border-right: none;
      border-bottom: none;
    }
    
    &.top-right {
      top: -3px;
      right: -3px;
      border-left: none;
      border-bottom: none;
    }
    
    &.bottom-left {
      bottom: -3px;
      left: -3px;
      border-right: none;
      border-top: none;
    }
    
    &.bottom-right {
      bottom: -3px;
      right: -3px;
      border-left: none;
      border-top: none;
    }
  }
}

@keyframes scanning {
  0% {
    top: 0;
  }
  100% {
    top: calc(100% - 2px);
  }
}

.scan-tips {
  margin-top: 30px;
  
  .tips-text {
    color: #fff;
    font-size: 14px;
    text-align: center;
  }
}

.action-buttons {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  
  .action-btn {
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    border: none;
    
    &.primary-btn {
      background-color: #007AFF;
      color: #fff;
      
      &:disabled {
        background-color: #ccc;
      }
    }
    
    &.secondary-btn {
      background-color: rgba(255, 255, 255, 0.1);
      color: #fff;
      border: 1px solid rgba(255, 255, 255, 0.3);
    }
  }
}

.recent-records {
  background-color: #fff;
  border-radius: 15px 15px 0 0;
  padding: 20px;
  max-height: 200px;
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    text {
      margin-left: 8px;
      font-size: 16px;
      font-weight: bold;
      color: var(--text-color-primary);
    }
  }
  
  .record-list {
    .record-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid var(--border-color);
      
      &:last-child {
        border-bottom: none;
      }
      
      .record-info {
        flex: 1;
        
        .coupon-name {
          display: block;
          font-size: 14px;
          color: var(--text-color-primary);
          margin-bottom: 4px;
        }
        
        .verify-time {
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }
    }
  }
}

.manual-input-modal {
  width: 300px;
  background-color: #fff;
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  
  .modal-header {
    padding: 20px;
    text-align: center;
    border-bottom: 1px solid var(--border-color);
    
    .modal-title {
      font-size: 18px;
      font-weight: bold;
      color: var(--text-color-primary);
    }
  }
  
  .modal-body {
    padding: 20px;
    
    .code-input {
      background-color: var(--background-color);
      border-radius: var(--border-radius);
      padding: 10px;
    }
  }
  
  .modal-footer {
    display: flex;
    border-top: 1px solid var(--border-color);
    
    .modal-btn {
      flex: 1;
      height: 50px;
      border: none;
      font-size: 16px;
      
      &.cancel-btn {
        background-color: #f5f5f5;
        color: var(--text-color-primary);
      }
      
      &.confirm-btn {
        background-color: var(--primary-color);
        color: #fff;
      }
    }
  }
}

.result-modal {
  width: 300px;
  background-color: #fff;
  border-radius: var(--border-radius-lg);
  padding: 30px 20px;
  text-align: center;
  
  .result-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    
    &.success {
      background-color: #52c41a;
    }
    
    &.error {
      background-color: #ff4d4f;
    }
  }
  
  .result-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 15px;
    color: var(--text-color-primary);
  }
  
  .result-content {
    text-align: left;
    margin-bottom: 20px;
    
    .result-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .label {
        font-size: 14px;
        color: var(--text-color-secondary);
      }
      
      .value {
        font-size: 14px;
        color: var(--text-color-primary);
        font-weight: bold;
      }
    }
  }
  
  .result-message {
    font-size: 14px;
    color: var(--text-color-secondary);
    margin-bottom: 20px;
  }
  
  .result-btn {
    width: 100%;
    height: 44px;
    background-color: var(--primary-color);
    color: #fff;
    border: none;
    border-radius: var(--border-radius);
    font-size: 16px;
  }
}
</style>